<?php

namespace app\api\logic;
use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Db;

class KolMessageLogic extends BasicLogic
{

    /**
     * @desc   达人合作表修改时发送http请求
     * @author xx
     * @date 2025-08-24
     */
    public function get_cooperate_info($params){
        htmlLog(['data'=>$params],OPERATE_LOG . date('Ym') . '/get_cooperate_info/' . date('Ymd') . '.txt');
        // update 2025-08-19 新增17号店铺的合作数据
        $params['shop_id'] = 17;
        self::edit_cooperate_17($params);
    }

    /**
     * @desc   达人合作表新增时发送http请求
     * @author xx
     * @date 2025-08-24
     */
    public function add_cooperate_info($params){
        htmlLog(['data'=>$params],OPERATE_LOG . date('Ym') . '/add_cooperate_info/' . date('Ymd') . '.txt');
        // update 2025-08-19 新增17号店铺的合作数据
        $params['shop_id'] = 17;
        self::sync_cooperate_17($params);
    }



    /**
     * @desc     接口拉取达人合作信息
     * @author   xx
     * @date     2025-08-13
     */
    public function get_wiki_token($params=[]){
        $basic_url             = Config('Logisticskey.fei_shu.basic_url');
        $wiki_token            = $params['wiki_token']??'';
        $token                 = (new FeiShuMessageLogic())->get_app_access_token();
        $url                   = $basic_url.'/wiki/v2/spaces/get_node/?obj_type=wiki&token='.$wiki_token;
        $res                   = HttpUtil::getFeiShu($url,$token,[]);
        $obj_token             = $res['data']['node']['obj_token']??'';
        return   $obj_token;

    }

    /**
     * @desc     接口拉取达人合作信息
     * @author   xx
     * @date     2025-08-13
     */
    public function cooperate_info($params=[]){
       $wiki_token             =  Config('Logisticskey.feishu_tables.coope_wiki_token');
       $obj_token              =  self::get_wiki_token(['wiki_token'=>$wiki_token]);
       if(!$obj_token)         return $this->jsonMessage(201,false,'暂无wiki授权','');
        $basic_url             = Config('Logisticskey.fei_shu.basic_url');
        $get_table_list        = Config('Logisticskey.fei_shu.get_table_list');
        $shop_id               = $params['shop_id']??'';
        $table_token           = $obj_token;
        $feishu_cooperate_table =  Config('Logisticskey.feishu_tables.cooperate_table_id');
        $table_id              = $feishu_cooperate_table[$shop_id]??'';
        $token                 = (new FeiShuMessageLogic())->get_app_access_token();
        $url                   = $basic_url.$get_table_list.$table_token.'/tables/'.$table_id.'/records';
        $res                   = HttpUtil::getFeiShu($url,$token,[]);
        if($res['code']==0){
            $list = $res['data']['items'];
            foreach($list as $v){
                $info   =  $v['fields'];
                if(!isset($info['博主账户名称']) && !isset($info['Handle'])) continue;
                $info['shop_id'] = $shop_id;
                //推动数据到队列;
                MqTaskPushLogic::mq_task_push(
                    '',
                    MqQueueName::QUEUE_ORDER_KOL_INFO_QUEUE,
                    json_encode($info, JSON_UNESCAPED_UNICODE),
                false
                );
            }
            return true;
        }
    }



    /**
     * @desc     达人合作数据消费队列
     * @author   xx
     * @date     2025-08-14
     */
    public function cooperate_data_consumer($info){
           //合作表数据分别写入达人表和合作表
           $shop_id  = $info['shop_id']??'';
           if($shop_id==17){
               self::kol_cooperate_17($info);
           }elseif($shop_id==18){
               self::kol_cooperate_18($info);
           }
           return  true;
    }

    //获取17号店铺数据
    public function kol_cooperate_17($info){
        $link                      = $info['主页链接']['link']??'';
        $admin_id                  = $info['建联人']['0']['id']??'';
        $cooperate_type_value      = $info['合作方式']??'';
        $publish_url               = $info['发布链接']??'';
        $sku                       = $info['寄件SKU']??'';
        $is_out_value              = $info['是否超时'][0]['text']??'';
        $fulfillment_status_cn     = $info['物流状态'][0]??'';
        $cooperate_status_value    = $info['合作状态']??'';
        $email                     = $info['联系方式']??'';
        $shop_id                   = $info['shop_id']??'';
        $publish_time              = $info['发布日期']??null;
        $cooperate_time            = $info['合作日期']??null;
        $expire_time               = $info['超时日期']??null;
        $expert_name               = $info['博主账户名称']??'';
        $expert_name               = str_replace(["\r", "\n", " "], '', $expert_name);
        if(strlen($expire_time)<8){
            $expire_time = null;
        }

        if($publish_time){
            $publish_time    = date('Y-m-d',$publish_time/1000);
        }

        if($cooperate_time){
            $cooperate_time = date('Y-m-d',$cooperate_time/1000);
        }
        if($expire_time){
            $expire_time    = date('Y-m-d',$expire_time/1000);
        }

        //通过链接获取平台ID
        if(strpos($link,'instagram')){
            $platform_id = 3;
        }elseif(strpos($link,'tiktok')){
            $platform_id = 1;
        }elseif(strpos($link,'youtube')){
            $platform_id = 2;
        }else{
            $platform_id = 0;
        }

        //合作方式
        if($cooperate_type_value=='免费置换'){
            $cooperate_type = 1;
        }elseif($cooperate_type_value=='付费合作'){
            $cooperate_type = 2;
        }elseif($cooperate_type_value=='10%佣金'){
            $cooperate_type = 3;
        }else{
            $cooperate_type = 0;
        }

        if ($sku) {
            $order_numbers_raw = trim($sku);
            $order_numbers_filtered = array_filter(explode("\n", $order_numbers_raw), 'trim');
            $sku  = implode(',',$order_numbers_filtered);
            $spu_info = current($order_numbers_filtered);
            $spu_info = explode('-', $spu_info);
            $spu      = $spu_info[0]??'';
        }

        if($is_out_value=='是'){
            $is_out= 2;
        }elseif($is_out_value=='否'){
            $is_out= 1;
        }else{
            $is_out= 0;
        }

        $fulfillment_status_arr  = Config('Logisticskey.feishu_track_status');
        $fulfillment_status      = $fulfillment_status_arr[$fulfillment_status_cn]??'';

        //物流状态
        if($fulfillment_status=='待发货'){
            $fulfillment_status=1;
        }elseif($fulfillment_status=='已签收'){
            $fulfillment_status = 3;
        }elseif($fulfillment_status=='运输中'){
            $fulfillment_status = 2;
        }elseif($fulfillment_status=='异常'){
            $fulfillment_status = 4;
        }


        //合作状态
        if($cooperate_status_value=='确认合作'){
            $cooperate_status=2;
        }elseif($cooperate_status_value=='取消合作'){
            $cooperate_status = 4;
        }elseif($cooperate_status_value=='已完成'){
            $cooperate_status = 3;
        }elseif($cooperate_status_value=='议价中'){
            $cooperate_status = 1;
        }else{
            $cooperate_status = 0;
        }



        $fb_admin_id = Db::name('system_admin')->where(['open_id'=>$admin_id])->value('id');
        $insert_kol  = [
            'expert_name' => $expert_name??'',
            'link'        => $link ? json_encode([$link]) :'',
            'fb_admin_id' => $fb_admin_id??'',
            'platform_id' => $platform_id??'',
            'email'       => $email??'',
            'shop_id'     => $shop_id??'',
            'update_time' => date("Y-m-d H:i:s",time()),
            'create_time' => date("Y-m-d H:i:s",time()),
        ];
        $where          = [];
        $where[]        = ['expert_name', 'like', '%' . $expert_name . '%'];
        $exist_kol_info = Db::name('tik_kol')->where($where)->find();
        if(!$exist_kol_info){
            $inset_id = Db::name('tik_kol')->insertGetId($insert_kol);
            $expert_id = 'k_'.$inset_id;
            Db::name('tik_kol')->where(['id'=>$inset_id])->update(
                [
                    'expert_id'=>$expert_id
                ]
            );
        }else{
            $expert_id =  $exist_kol_info['expert_id']??'';
        }

        $insert_kol_cooperate = [
            'shop_id'            =>$shop_id,
            'expert_id'          =>$expert_id,
            'expert_name'        =>$expert_name??'',
            'creation_code'      =>'',
            'platform_id'        =>$platform_id,
            'cooperate_status'   =>$cooperate_status,
            'cooperate_type'     =>$cooperate_type,
            'publish_url'        =>$publish_url,
            'link'              => $link ? :'',
            'spu'                =>$spu,
            'sku'                =>$sku,
            'is_out'             =>$is_out,
            'fb_admin_id'        =>$fb_admin_id,
            'fulfillment_status' =>$fulfillment_status,
            'publish_time'       =>$publish_time,
            'cooperate_time'     =>$cooperate_time,
            'expire_time'        =>$expire_time,
            'update_time'        =>date("Y-m-d H:i:s",time()),
            'create_time'        =>date("Y-m-d H:i:s",time()),
        ];
        Db::name('tik_kol_cooperate')->insert($insert_kol_cooperate);
        return  true;
    }


    //获取17号店铺数据新增
    public function sync_cooperate_17($info){
        $link                      = $info['link']??'';
        $admin_id                  = $info['fb_admin']??'';
        $cooperate_type_value      = $info['cooperate_type']??'';
        $publish_url               = $info['publish_url']??'';
        $sku                       = $info['sku']??'';
        $spu                       = $info['spu']??'';
        $is_out_value              = $info['is_out']??'';
        $fulfillment_status_cn     = $info['fulfillment_status']??'';
        $cooperate_status_value    = $info['cooperate_status']??'';
        $email                     = $info['email']??'';
        $shop_id                   = $info['shop_id']??'';
        $publish_time              = $info['publish_time']??null;
        $cooperate_time            = $info['cooperate_date']??null;
        $expire_time               = $info['expire_time']??null;
        $expert_name               = $info['expert_name']??'';
        $expert_name               = str_replace(["\r", "\n", " "], '', $expert_name);
        if(strlen($expire_time)<8){
            $expire_time = null;
        }
        $expert_name   = trim($expert_name);
        $admin_id      = trim($admin_id);

        if($publish_time){
            $publish_time    = date('Y-m-d',strtotime($publish_time));
        }

        if($cooperate_time){
            $cooperate_time = date('Y-m-d',strtotime($cooperate_time));
        }
        if($expire_time){
            $expire_time    = date('Y-m-d',strtotime($expire_time));
        }

        //通过链接获取平台ID
        if(strpos($link,'instagram')){
            $platform_id = 3;
        }elseif(strpos($link,'tiktok')){
            $platform_id = 1;
        }elseif(strpos($link,'youtube')){
            $platform_id = 2;
        }else{
            $platform_id = 0;
        }

        //合作方式
        if($cooperate_type_value=='免费置换'){
            $cooperate_type = 1;
        }elseif($cooperate_type_value=='付费合作'){
            $cooperate_type = 2;
        }elseif($cooperate_type_value=='10%佣金'){
            $cooperate_type = 3;
        }else{
            $cooperate_type = 0;
        }

        if ($sku) {
            $order_numbers_raw = trim($sku);
            $order_numbers_filtered = array_filter(explode("\n", $order_numbers_raw), 'trim');
            $sku  = implode(',',$order_numbers_filtered);
        }

        if($is_out_value=='是'){
            $is_out= 2;
        }elseif($is_out_value=='否'){
            $is_out= 1;
        }else{
            $is_out= 0;
        }

        $fulfillment_status_arr  = Config('Logisticskey.feishu_track_status');
        $fulfillment_status      = $fulfillment_status_arr[$fulfillment_status_cn]??'';

        //物流状态
        if($fulfillment_status=='待发货'){
            $fulfillment_status=1;
        }elseif($fulfillment_status=='已签收'){
            $fulfillment_status = 3;
        }elseif($fulfillment_status=='运输中'){
            $fulfillment_status = 2;
        }elseif($fulfillment_status=='异常'){
            $fulfillment_status = 4;
        }


        //合作状态
        if($cooperate_status_value=='确认合作'){
            $cooperate_status=2;
        }elseif($cooperate_status_value=='取消合作'){
            $cooperate_status = 4;
        }elseif($cooperate_status_value=='已完成'){
            $cooperate_status = 3;
        }elseif($cooperate_status_value=='议价中'){
            $cooperate_status = 1;
        }else{
            $cooperate_status = 0;
        }



        $fb_admin_id = Db::name('system_admin')->where('username','like', '%' . $admin_id . '%')->value('id');
        $insert_kol  = [
            'expert_name' => $expert_name??'',
            'link'        => $link ? json_encode([$link]) :'',
            'fb_admin_id' => $fb_admin_id??'',
            'platform_id' => $platform_id??'',
            'email'       => $email??'',
            'shop_id'     => $shop_id??'',
            'update_time' => date("Y-m-d H:i:s",time()),
            'create_time' => date("Y-m-d H:i:s",time()),
        ];

        $where          = [];
        $where[]        = ['expert_name', 'like', '%' . $expert_name . '%'];
        $exist_kol_info = Db::name('tik_kol')->where($where)->find();
        if(!$exist_kol_info){
            $inset_id = Db::name('tik_kol')->insertGetId($insert_kol);
            $expert_id = 'k_'.$inset_id;
            Db::name('tik_kol')->where(['id'=>$inset_id])->update(
                [
                    'expert_id'=>$expert_id
                ]
            );
        }else{
            $expert_id =  $exist_kol_info['expert_id']??'';
        }

        $insert_kol_cooperate = [
            'shop_id'            =>$shop_id,
            'expert_id'          =>$expert_id,
            'expert_name'        =>$expert_name??'',
            'creation_code'      =>'',
            'platform_id'        =>$platform_id,
            'cooperate_status'   =>$cooperate_status,
            'cooperate_type'     =>$cooperate_type,
            'publish_url'        =>$publish_url,
            'link'              => $link ? :'',
            'spu'                =>$spu,
            'sku'                =>$sku,
            'is_out'             =>$is_out,
            'fb_admin_id'        =>$fb_admin_id,
            'fulfillment_status' =>$fulfillment_status,
            'publish_time'       =>$publish_time,
            'cooperate_time'     =>$cooperate_time,
            'expire_time'        =>$expire_time,
            'update_time'        =>date("Y-m-d H:i:s",time()),
            'create_time'        =>date("Y-m-d H:i:s",time()),
        ];
        Db::name('tik_kol_cooperate')->insert($insert_kol_cooperate);
        return  true;
    }

    //获取17号店铺数据修改
    public function edit_cooperate_17($info){
        $link                      = $info['link']??'';
        $admin_id                  = $info['fb_admin']??'';
        $cooperate_type_value      = $info['cooperate_type']??'';
        $publish_url               = $info['publish_url']??'';
        $sku                       = $info['sku']??'';
        $spu                       = $info['spu']??'';
        $is_out_value              = $info['is_out']??'';
        $fulfillment_status_cn     = $info['fulfillment_status']??'';
        $cooperate_status_value    = $info['cooperate_status']??'';
        $email                     = $info['email']??'';
        $shop_id                   = $info['shop_id']??'';
        $publish_time              = $info['publish_time']??null;
        $cooperate_time            = $info['cooperate_date']??null;
        $expire_time               = $info['expire_time']??null;
        $expert_name               = $info['expert_name']??'';
        $expert_name               = str_replace(["\r", "\n", " "], '', $expert_name);
        if(strlen($expire_time)<8){
            $expire_time = null;
        }
        $expert_name   = trim($expert_name);
        $admin_id      = trim($admin_id);

        if($publish_time){
            $publish_time    = date('Y-m-d',strtotime($publish_time));
        }

        if($cooperate_time){
            $cooperate_time = date('Y-m-d',strtotime($cooperate_time));
        }
        if($expire_time){
            $expire_time    = date('Y-m-d',strtotime($expire_time));
        }

        //通过链接获取平台ID
        if(strpos($link,'instagram')){
            $platform_id = 3;
        }elseif(strpos($link,'tiktok')){
            $platform_id = 1;
        }elseif(strpos($link,'youtube')){
            $platform_id = 2;
        }else{
            $platform_id = 0;
        }

        //合作方式
        if($cooperate_type_value=='免费置换'){
            $cooperate_type = 1;
        }elseif($cooperate_type_value=='付费合作'){
            $cooperate_type = 2;
        }elseif($cooperate_type_value=='10%佣金'){
            $cooperate_type = 3;
        }else{
            $cooperate_type = 0;
        }

        if ($sku) {
            $order_numbers_raw = trim($sku);
            $order_numbers_filtered = array_filter(explode("\n", $order_numbers_raw), 'trim');
            $sku  = implode(',',$order_numbers_filtered);
        }

        if($is_out_value=='是'){
            $is_out= 2;
        }elseif($is_out_value=='否'){
            $is_out= 1;
        }else{
            $is_out= 0;
        }

        $fulfillment_status_arr  = Config('Logisticskey.feishu_track_status');
        $fulfillment_status      = $fulfillment_status_arr[$fulfillment_status_cn]??'';

        //物流状态
        if($fulfillment_status=='待发货'){
            $fulfillment_status=1;
        }elseif($fulfillment_status=='已签收'){
            $fulfillment_status = 3;
        }elseif($fulfillment_status=='运输中'){
            $fulfillment_status = 2;
        }elseif($fulfillment_status=='异常'){
            $fulfillment_status = 4;
        }


        //合作状态
        if($cooperate_status_value=='确认合作'){
            $cooperate_status=2;
        }elseif($cooperate_status_value=='取消合作'){
            $cooperate_status = 4;
        }elseif($cooperate_status_value=='已完成'){
            $cooperate_status = 3;
        }elseif($cooperate_status_value=='议价中'){
            $cooperate_status = 1;
        }else{
            $cooperate_status = 0;
        }

        $fb_admin_id = Db::name('system_admin')->where('username','like', '%' . $admin_id . '%')->value('id');
        $insert_kol  = [
            'expert_name' => $expert_name??'',
            'link'        => $link ? json_encode([$link]) :'',
            'fb_admin_id' => $fb_admin_id??'',
            'platform_id' => $platform_id??'',
            'email'       => $email??'',
            'shop_id'     => $shop_id??'',
            'update_time' => date("Y-m-d H:i:s",time()),
            'create_time' => date("Y-m-d H:i:s",time()),
        ];

        $where          = [];
        $where[]        = ['expert_name', 'like', '%' . $expert_name . '%'];
        $exist_kol_info = Db::name('tik_kol')->where($where)->find();
        if(!$exist_kol_info){
            $inset_id = Db::name('tik_kol')->insertGetId($insert_kol);
            $expert_id = 'k_'.$inset_id;
            Db::name('tik_kol')->where(['id'=>$inset_id])->update(
                [
                    'expert_id'=>$expert_id
                ]
            );
        }else{
            $expert_id = $exist_kol_info['expert_id']??'';
        }

        $edit_kol_cooperate = [
            'shop_id'            =>$shop_id,
            'expert_id'          =>$expert_id,
            'expert_name'        =>$expert_name??'',
            'creation_code'      =>'',
            'platform_id'        =>$platform_id,
            'cooperate_status'   =>$cooperate_status,
            'cooperate_type'     =>$cooperate_type,
            'publish_url'        =>$publish_url,
            'link'               =>$link ? :'',
            'spu'                =>$spu,
            'sku'                =>$sku,
            'is_out'             =>$is_out,
            'fb_admin_id'        =>$fb_admin_id,
            'fulfillment_status' =>$fulfillment_status,
            'publish_time'       =>$publish_time,
            'cooperate_time'     =>$cooperate_time,
            'expire_time'        =>$expire_time,
            'update_time'        =>date("Y-m-d H:i:s",time()),
        ];
        Db::name('tik_kol_cooperate')->where(['expert_id'=>$expert_id,'spu'=>$spu])->update($edit_kol_cooperate);
        return  true;
    }



    //获取18号店铺数据
    public function kol_cooperate_18($info){
        $link                      = $info['Link']['link']??'';
        $admin_id                  = $info['负责人']['0']['id']??'';
        $cooperate_type_value      = $info['合作状态']??'';
        $sku                       = $info['发货SKU']??'';
        $is_out_value              = $info['是否超时'][0]['text']??'';
        $publish_url               = $info['Post link'][0]['link']??'';
        $fulfillment_status_cn     = $info['包裹状态'][0]??'';
        $cooperate_status_value    = $info['合作状态']??'';
        $email                     = $info['Contact']??'';
        $shop_id                   = $info['shop_id']??'';
        $deliverables              = $info['Deliverables']??'';
        $fun                       = $info['Followers(k)']??'0';
        $payment_price             = $info['Price($)']??'0';
        $publish_time              = $info['Post date']??null;
        $cooperate_time            = $info['合作日期']??null;
        $expire_time               = $info['应发日期']??null;
        $expert_name               = $info['Handle']??'';
        $expert_name               = str_replace(["\r", "\n", " "], '', $expert_name);
        if(strlen($expire_time)<8){
            $expire_time = null;
        }

        if($publish_time){
            $publish_time    = date('Y-m-d',$publish_time/1000);
        }

        if($cooperate_time){
            $cooperate_time = date('Y-m-d',$cooperate_time/1000);
        }
        if($expire_time){
            $expire_time    = date('Y-m-d',$expire_time/1000);
        }

        //通过链接获取平台ID
        if(strpos($link,'instagram')){
            $platform_id = 3;
        }elseif(strpos($link,'tiktok')){
            $platform_id = 1;
        }elseif(strpos($link,'youtube')){
            $platform_id = 2;
        }else{
            $platform_id = 0;
        }

        //合作方式
        if($cooperate_type_value=='$0'){
            $cooperate_type = 1;
        }elseif($cooperate_type_value!='$0'){
            $cooperate_type = 2;
        }else{
            $cooperate_type = 0;
        }

        if ($sku) {
            $order_numbers_raw = trim($sku);
            $order_numbers_filtered = array_filter(explode("\n", $order_numbers_raw), 'trim');
            $sku  = implode(',',$order_numbers_filtered);
            $spu_info = current($order_numbers_filtered);
            $spu_info = explode('-', $spu_info);
            $spu      = $spu_info[0]??'';
        }

        if($is_out_value=='是'){
            $is_out= 2;
        }elseif($is_out_value=='否'){
            $is_out= 1;
        }else{
            $is_out= 0;
        }

        $fulfillment_status_arr  = Config('Logisticskey.feishu_track_status');
        $fulfillment_status      = $fulfillment_status_arr[$fulfillment_status_cn]??'';

        //物流状态
        if($fulfillment_status=='待发货'){
            $fulfillment_status=1;
        }elseif($fulfillment_status=='已签收'){
            $fulfillment_status = 3;
        }elseif($fulfillment_status=='运输中'){
            $fulfillment_status = 2;
        }elseif($fulfillment_status=='异常'){
            $fulfillment_status = 4;
        }


        //合作状态
        if($cooperate_status_value=='确认合作'){
            $cooperate_status=2;
        }elseif($cooperate_status_value=='取消合作'){
            $cooperate_status = 4;
        }elseif($cooperate_status_value=='已完成'){
            $cooperate_status = 3;
        }elseif($cooperate_status_value=='议价中'){
            $cooperate_status = 1;
        }else{
            $cooperate_status = 0;
        }



        $fb_admin_id = Db::name('system_admin')->where(['open_id'=>$admin_id])->value('id');
        $insert_kol  = [
            'expert_name' => $expert_name??'',
            'link'        => $link ? json_encode([$link]) :'',
            'fb_admin_id' => $fb_admin_id??'',
            'platform_id' => $platform_id??'',
            'email'       => $email??'',
            'shop_id'     => $shop_id??'',
            'fan'         => $fun??'',
            'update_time' => date("Y-m-d H:i:s",time()),
            'create_time' => date("Y-m-d H:i:s",time()),
        ];
        $where          = [];
        $where[]        = ['expert_name', 'like', '%' . $expert_name . '%'];
        $exist_kol_info = Db::name('tik_kol')->where($where)->find();
        if(!$exist_kol_info){
            $inset_id = Db::name('tik_kol')->insertGetId($insert_kol);
            $expert_id = 'k_'.$inset_id;
            Db::name('tik_kol')->where(['id'=>$inset_id])->update(
                [
                    'expert_id'=>$expert_id
                ]
            );
        }else{
            $expert_id =  $exist_kol_info['expert_id']??'';
        }

        $insert_kol_cooperate = [
            'shop_id'            =>$shop_id,
            'expert_id'          =>$expert_id,
            'expert_name'        =>$expert_name??'',
            'creation_code'      =>'',
            'platform_id'        =>$platform_id,
            'cooperate_status'   =>$cooperate_status,
            'cooperate_type'     =>$cooperate_type,
            'link'               => $link ?:'',
            'spu'                =>$spu,
            'payment_price'      =>$payment_price,
            'sku'                =>$sku,
            'is_out'             =>$is_out,
            'deliverables'       =>$deliverables,
            'fb_admin_id'        =>$fb_admin_id,
            'fulfillment_status' =>$fulfillment_status,
            'publish_time'       =>$publish_time,
            'publish_url'        =>$publish_url,
            'cooperate_time'     =>$cooperate_time,
            'expire_time'        =>$expire_time,
            'update_time'        =>date("Y-m-d H:i:s",time()),
            'create_time'        =>date("Y-m-d H:i:s",time()),
        ];
        Db::name('tik_kol_cooperate')->insert($insert_kol_cooperate);
        return  true;
    }


    /**
     * @desc     接口拉取达人订单信息
     * @author   xx
     * @date     2025-08-15
     */
    public function cooperate_order($params=[]){
        $wiki_token     =  Config('Logisticskey.feishu_tables.coope_wiki_token');
        $obj_token      =  self::get_wiki_token(['wiki_token'=>$wiki_token]);
        if(!$obj_token)    return $this->jsonMessage(201,false,'暂无wiki授权','');
        $basic_url              = Config('Logisticskey.fei_shu.basic_url');
        $get_table_list         = Config('Logisticskey.fei_shu.get_table_list');
        $shop_id                = $params['shop_id']??'';
        $table_token            = $obj_token;
        $feishu_cooperate_table =  Config('Logisticskey.feishu_tables.order_table_id');
        $table_id               = $feishu_cooperate_table[$shop_id]??'';
        $token                  = (new FeiShuMessageLogic())->get_app_access_token();
        $url                    = $basic_url.$get_table_list.$table_token.'/tables/'.$table_id.'/records';
        $res                    = HttpUtil::getFeiShu($url,$token,[]);
        if($res['code']==0){
            $list = $res['data']['items'];
            foreach($list as $v){
                $info   =  $v['fields'];
                if(!isset($info['达人ID']) && !isset($info['达人handle'])) continue;
                $info['shop_id'] = $shop_id;
                //推动数据到队列;
                MqTaskPushLogic::mq_task_push(
                    '',
                    MqQueueName::QUEUE_ORDER_KOL_TRACK_QUEUE,
                    json_encode($info, JSON_UNESCAPED_UNICODE),
                    false
                );
            }
            return true;
        }
    }



    /**
     * @desc     接口拉取达人订单信息
     * @author   xx
     * @date     2025-08-15
     */
    public function cooperate_order_consumer($info){
        $list = Db::name('tik_kol_order')->select()->toArray();
        //合作表数据分别写入达人表和合作表
        $shop_id  = $info['shop_id']??'';
        if($shop_id==17){
            self::kol_order_17($info);
        }elseif($shop_id==18){
            self::kol_order_18($info);
        }
        return  true;

    }


    //达人订单;
    public function kol_order_17($info){
        $link                      = $info['链接']['0']['link']??'';
        $admin_id                  = $info['建联人']['0']['id']??'';
        $sku                       = $info['发货SKU']??'';
        $country                   = $info['国家']??'';
        $track_number              = $info['物流单号']??'';
        $track_name                = $info['物流商']??'';
        $fulfillment_status        = $info['状态']??'';
        $phone                     = $info['电话']??'';
        $province                  = $info['省份']??'';
        $city                      = $info['市区']??'';
        $customer_name             = $info['真实姓名']??'';
        $email                     = $info['邮箱']['0']['text']??'';
        $address                   = $info['详细地址']??'';
        $zip                       = $info['邮编']??'';
        $remarks                   = $info['备注']??'';
        $remark_exception          = $info['缺货/异常/退件备注']??'';
        $shop_id                   = $info['shop_id']??'';
        $publish_time              = $info['发货日期']??null;
        $cooperate_time            = $info['合作日期']??null;
        $receive_time              = $info['签收日期']??null;
        $last_time                 = $info['截至日期']??null;
        $expert_name               = $info['达人ID']??'';
        $expert_name               = str_replace(["\r", "\n", " "], '', $expert_name);
        if(strlen($last_time)<8){
            $last_time = null;
        }

        if($publish_time){
            $publish_time    = date('Y-m-d',$publish_time/1000);
        }

        if($cooperate_time){
            $cooperate_time = date('Y-m-d',$cooperate_time/1000);
        }
        if($last_time){
            $last_time    = date('Y-m-d',$last_time/1000);
        }

        if($receive_time){
            $receive_time    = date('Y-m-d',$receive_time/1000);
        }

        //通过链接获取平台ID
        if(strpos($link,'instagram')){
            $platform_id = 3;
        }elseif(strpos($link,'tiktok')){
            $platform_id = 1;
        }elseif(strpos($link,'youtube')){
            $platform_id = 2;
        }else{
            $platform_id = 0;
        }

        if ($sku) {
            $order_numbers_raw = trim($sku);
            $order_numbers_filtered = array_filter(explode("\n", $order_numbers_raw), 'trim');
            $sku  = implode(',',$order_numbers_filtered);
            $spu_info = current($order_numbers_filtered);
            $spu_info = explode('-', $spu_info);
            $spu      = $spu_info[0]??'';
        }


        $fulfillment_status_arr  = Config('Logisticskey.feishu_track_status');
        $fulfillment_status      = $fulfillment_status_arr[$fulfillment_status]??'';

        //物流状态
        if($fulfillment_status=='待发货'){
            $fulfillment_status=1;
        }elseif($fulfillment_status=='已签收'){
            $fulfillment_status = 3;
        }elseif($fulfillment_status=='运输中'){
            $fulfillment_status = 2;
        }elseif($fulfillment_status=='异常'){
            $fulfillment_status = 4;
        }

        $fb_admin_id = Db::name('system_admin')->where(['open_id'=>$admin_id])->value('id');
        $insert_kol  = [
            'expert_name' => $expert_name??'',
            'link'        => $link ?:'',
            'fb_admin_id' => $fb_admin_id??'',
            'platform_id' => $platform_id??'',
            'shop_id'     => $shop_id??'',
            'update_time' => date("Y-m-d H:i:s",time()),
            'create_time' => date("Y-m-d H:i:s",time()),
        ];
        $where          = [];
        $where[]        = ['expert_name', 'like', '%' . $expert_name . '%'];
        $exist_kol_info = Db::name('tik_kol')->where($where)->find();
        if(!$exist_kol_info){
            $inset_id = Db::name('tik_kol')->insertGetId($insert_kol);
            $expert_id = 'k_'.$inset_id;
            Db::name('tik_kol')->where(['id'=>$inset_id])->update(
                [
                    'expert_id'=>$expert_id
                ]
            );
        }else{
            $expert_id =  $exist_kol_info['expert_id']??'';
        }
        $email = self::normalizeEmail($email);
        $insert_kol_order = [
            'shop_id'            =>$shop_id,
            'expert_id'          =>$expert_id,
            'expert_name'        =>$expert_name??'',
            'platform_id'        =>$platform_id,
            'link'               => $link ?:'',
            'spu'                =>$spu,
            'sku'                =>$sku,
            'track_number'       =>$track_number,
            'track_name'         =>$track_name,
            'customer_name'      =>$customer_name,
            'email'              =>$email,
            'phone'              =>$phone,
            'country'            =>$country,
            'province'           =>$province,
            'city'               =>$city,
            'zip'                =>$zip,
            'remarks'            =>$remarks,
            'remark_exception'   =>$remark_exception,
            'address'            =>$address,
            'fulfillment_status' =>$fulfillment_status,
            'fb_admin_id'        =>$fb_admin_id,
            'publish_time'       =>$publish_time,
            'cooperate_time'     =>$cooperate_time,
            'receive_time'       =>$receive_time,
            'last_time'          =>$last_time,
            'update_time'        =>date("Y-m-d H:i:s",time()),
            'create_time'        =>date("Y-m-d H:i:s",time()),
        ];

        $exist_kol_order = Db::name('tik_kol_order')->where(['expert_name'=>$expert_name,'track_number'=>$track_number])->find();
        if($exist_kol_order){
            Db::name('tik_kol_order')->where(['id'=>$exist_kol_order['id']])->update(
                $insert_kol_order
            );
        }else{
            Db::name('tik_kol_order')->insert($insert_kol_order);
        }
        return  true;
    }

    //达人订单;
    public function kol_order_18($info){
        $link                      = $info['link']['0']['link']??'';
        $admin_id                  = $info['对接人']['0']['id']??'';
        $sku                       = $info['发货SKU']??'';
        $country                   = $info['国家']??'';
        $track_number              = $info['物流单号']??'';
        $track_name                = $info['物流商']??'';
        $fulfillment_status        = $info['包裹状态']??'';
        $phone                     = $info['电话']??'';
        $province                  = $info['省']??'';
        $city                      = $info['市区']??'';
        $customer_name             = $info['姓名']??'';
        $email                     = $info['邮箱']['0']['text']??'';
        $address                   = $info['收货地址']??'';
        $zip                       = $info['邮编']??'';
        $shop_id                   = $info['shop_id']??'';
        $publish_time              = $info['发货日期']??null;
        $cooperate_time            = $info['日期']??null;
        $receive_time              = $info['签收日期']??null;
        $last_time                 = $info['超时日期']??null;
        $expert_name               = $info['达人handle']??'';
        $expert_name               = str_replace(["\r", "\n", " "], '', $expert_name);
        if(strlen($last_time)<8){
            $last_time = null;
        }

        if($publish_time){
            $publish_time    = date('Y-m-d',$publish_time/1000);
        }

        if($cooperate_time){
            $cooperate_time = date('Y-m-d',$cooperate_time/1000);
        }
        if($last_time){
            $last_time    = date('Y-m-d',$last_time/1000);
        }

        if($receive_time){
            $receive_time    = date('Y-m-d',$receive_time/1000);
        }

        //通过链接获取平台ID
        if(strpos($link,'instagram')){
            $platform_id = 3;
        }elseif(strpos($link,'tiktok')){
            $platform_id = 1;
        }elseif(strpos($link,'youtube')){
            $platform_id = 2;
        }else{
            $platform_id = 0;
        }

        if ($sku) {
            $order_numbers_raw = trim($sku);
            $order_numbers_filtered = array_filter(explode("\n", $order_numbers_raw), 'trim');
            $sku  = implode(',',$order_numbers_filtered);
            $spu_info = current($order_numbers_filtered);
            $spu_info = explode('-', $spu_info);
            $spu      = $spu_info[0]??'';
        }


        $fulfillment_status_arr  = Config('Logisticskey.feishu_track_status');
        $fulfillment_status      = $fulfillment_status_arr[$fulfillment_status]??'';

        //物流状态
        if($fulfillment_status=='待发货'){
            $fulfillment_status=1;
        }elseif($fulfillment_status=='已签收'){
            $fulfillment_status = 3;
        }elseif($fulfillment_status=='运输中'){
            $fulfillment_status = 2;
        }elseif($fulfillment_status=='异常'){
            $fulfillment_status = 4;
        }

        $fb_admin_id = Db::name('system_admin')->where(['open_id'=>$admin_id])->value('id');
        $insert_kol  = [
            'expert_name' => $expert_name??'',
            'link'        => $link ?:'',
            'fb_admin_id' => $fb_admin_id??'',
            'platform_id' => $platform_id??'',
            'shop_id'     => $shop_id??'',
            'update_time' => date("Y-m-d H:i:s",time()),
            'create_time' => date("Y-m-d H:i:s",time()),
        ];
        $where          = [];
        $where[]        = ['expert_name', 'like', '%' . $expert_name . '%'];
        $exist_kol_info = Db::name('tik_kol')->where($where)->find();
        if(!$exist_kol_info){
            $inset_id = Db::name('tik_kol')->insertGetId($insert_kol);
            $expert_id = 'k_'.$inset_id;
            Db::name('tik_kol')->where(['id'=>$inset_id])->update(
                [
                    'expert_id'=>$expert_id
                ]
            );
        }else{
            $expert_id =  $exist_kol_info['expert_id']??'';
        }
        $email = self::normalizeEmail($email);
        $insert_kol_order = [
            'shop_id'            =>$shop_id,
            'expert_id'          =>$expert_id,
            'expert_name'        =>$expert_name??'',
            'platform_id'        =>$platform_id,
            'link'               => $link ?:'',
            'spu'                =>$spu,
            'sku'                =>$sku,
            'track_number'       =>$track_number,
            'track_name'         =>$track_name,
            'customer_name'      =>$customer_name,
            'email'              =>$email,
            'phone'              =>$phone,
            'country'            =>$country,
            'province'           =>$province,
            'city'               =>$city,
            'zip'                =>$zip,
            'address'            =>$address,
            'fulfillment_status' =>$fulfillment_status,
            'fb_admin_id'        =>$fb_admin_id,
            'publish_time'       =>$publish_time,
            'cooperate_time'     =>$cooperate_time,
            'receive_time'       =>$receive_time,
            'last_time'          =>$last_time,
            'update_time'        =>date("Y-m-d H:i:s",time()),
            'create_time'        =>date("Y-m-d H:i:s",time()),
        ];

        $exist_kol_order = Db::name('tik_kol_order')->where(['expert_name'=>$expert_name,'track_number'=>$track_number])->find();
        if($exist_kol_order){
            Db::name('tik_kol_order')->where(['id'=>$exist_kol_order['id']])->update(
                $insert_kol_order
            );
        }else{
            Db::name('tik_kol_order')->insert($insert_kol_order);
        }
        return  true;
    }



    /**
     * @desc     接口拉取达人订单信息
     * @author   xx
     * @date     2025-08-15
     */
    public function cooperate_video($params=[]){
        $wiki_token     =  Config('Logisticskey.feishu_tables.vedio_wiki_token');
        $obj_token      =  self::get_wiki_token(['wiki_token'=>$wiki_token]);
        if(!$obj_token)    return $this->jsonMessage(201,false,'暂无wiki授权','');
        $basic_url              = Config('Logisticskey.fei_shu.basic_url');
        $get_table_list         = Config('Logisticskey.fei_shu.get_table_list');
        $shop_id                = $params['shop_id']??'';
        $table_token            = $obj_token;
        $feishu_video_table     = Config('Logisticskey.feishu_tables.vedio_table_id');
        $table_id               = $feishu_video_table;
        $token                  = (new FeiShuMessageLogic())->get_app_access_token();
        $url                    = $basic_url.$get_table_list.$table_token.'/tables/'.$table_id.'/records';
        $res                    = HttpUtil::getFeiShu($url,$token,[]);
        if($res['code']==0){
            $list = $res['data']['items'];
            foreach($list as $v){
                $info   =  $v['fields'];
                if(!isset($info['达人ID']) || !$info['达人ID']) continue;
                 //推动数据到队列;
                 MqTaskPushLogic::mq_task_push(
                     '',
                     MqQueueName::QUEUE_ORDER_KOL_VIDEO_QUEUE,
                     json_encode($info, JSON_UNESCAPED_UNICODE),
                     false
                 );
            }
            return true;
        }
    }


    /**
     * @desc     接口拉取达人素材信息消费
     * @author   xx
     * @date     2025-08-15
     */
    public function cooperate_video_consumer($info){
        $sku                       = $info['SKU']??'';
        $video_url                 = $info['原视频链接']??'';
        $creation_code             = $info['网红代码']??'';
        $video_file                = $info['视频上传']??'';
        $fb_admin_arr              = $info['投放人员']??'';
        $remarks                   = $info['备注']??'';
        $publish_time              = $info['日期']??null;
        $admin_id                  = $info['负责人']['0']['id']??'';
        $expert_name               = $info['达人ID']??'';
        $expert_name               = str_replace(["\r", "\n", " "], '', $expert_name);
        if ($sku) {
            $order_numbers_raw = trim($sku);
            $order_numbers_filtered = array_filter(explode("\n", $order_numbers_raw), 'trim');
            $sku  = implode(',',$order_numbers_filtered);
            $spu_info = current($order_numbers_filtered);
            $spu_info = explode('-', $spu_info);
            $spu      = $spu_info[0]??'';
        }

        if($publish_time){
            $publish_time    = date('Y-m-d',$publish_time/1000);
        }


        $fb_admin_id    = Db::name('system_admin')->where(['open_id'=>$admin_id])->value('id');
        $fb_admin_names = $fb_admin_arr ? array_column($fb_admin_arr,'en_name'):'';
        $fb_admin_names = $fb_admin_names ? implode(',',$fb_admin_names) : '';
        $insert_kol  = [
            'expert_name' => $expert_name??'',
            'fb_admin_id' => $fb_admin_id??'',
            'update_time' => date("Y-m-d H:i:s",time()),
            'create_time' => date("Y-m-d H:i:s",time()),
        ];
        $where          = [];
        $where[]        = ['expert_name', 'like', '%' . $expert_name . '%'];
        $exist_kol_info = Db::name('tik_kol')->where($where)->find();
        if(!$exist_kol_info){
            $inset_id = Db::name('tik_kol')->insertGetId($insert_kol);
            $expert_id = 'k_'.$inset_id;
            Db::name('tik_kol')->where(['id'=>$inset_id])->update(
                [
                    'expert_id'=>$expert_id
                ]
            );
        }else{
            $expert_id =  $exist_kol_info['expert_id']??'';
        }

        $insert_kol_video = [
            'expert_id'          =>$expert_id,
            'expert_name'        =>$expert_name??'',
            'creation_code'      => $creation_code,
            'video_url'          =>$video_url,
            'spu'                =>$spu,
            'sku'                =>$sku,
            'remarks'            =>$remarks,
            'fb_admin_id'        =>$fb_admin_id,
            'fb_admin_names'     =>$fb_admin_names,
            'video_file'         =>$video_file ? json_encode($video_file,JSON_UNESCAPED_UNICODE):null,
            'publish_time'       =>$publish_time,
            'update_time'        =>date("Y-m-d H:i:s",time()),
            'create_time'        =>date("Y-m-d H:i:s",time()),
        ];

        $exist_kol_video = Db::name('tik_kol_video')->where(['expert_name'=>$expert_name,'sku'=>$sku])->find();
        if($exist_kol_video){
            Db::name('tik_kol_video')->where(['id'=>$exist_kol_video['id']])->update(
                $insert_kol_video
            );
            if($video_file){
                $message_info['video_id']   = $exist_kol_video['id'];
                $message_info['video_file'] = $video_file;
                //数据推送队列处理;
                MqTaskPushLogic::mq_task_push(
                    '',
                    MqQueueName::QUEUE_KOL_VIDEO_LOCAL_QUEUE,
                    $message_info,
                    false
                );
            }
        }else{
            $vedio_id = Db::name('tik_kol_video')->insertGetId($insert_kol_video);
            if($video_file){
                $message_info['video_id']   = $vedio_id;
                $message_info['video_file'] = $video_file;
                //数据推送队列处理;
                MqTaskPushLogic::mq_task_push(
                    '',
                    MqQueueName::QUEUE_KOL_VIDEO_LOCAL_QUEUE,
                    $message_info,
                    false
                );
            }
        }
        return  true;
    }


    /**
     * @desc     接口拉取达人素材信息消费
     * @author   xx
     * @date     2025-08-15
     */
    public function cooperate_video_local_consumer($info){
            $video_id = $info['video_id'] ??'';
            $tmp_url  = $info['video_file']['0']['tmp_url'] ??'';
            if(!$tmp_url)  return  true;
            //获取地址;
            $token                  = (new FeiShuMessageLogic())->get_app_access_token();
            $url                    = $tmp_url;
            $res                    = HttpUtil::getFeiShu($url,$token,[]);
            $video_url              = $res['data']['tmp_download_urls']['0']['tmp_download_url']??'';
            //视频上传到OSS服务器;
            $oss_url                = (new UploadTestLogic())->uploadVideoOSS(['url'=>$video_url]);
            if($oss_url){
                Db::name('tik_kol_video')->where(['id'=>$video_id])->update(
                    [
                        'storage_url'=>$oss_url,
                        'update_time'=>date("Y-m-d H:i:s",time()),
                    ]
                );
            }
            return   true;

    }

    /**
     * @desc     接口拉取达人素材数据
     * @author   xx
     * @date     2025-08-13
     */
    public function cooperate_video_produce(){
           $where   = [];
           $where[] = ['video_file','<>',''];
           $where[] = ['storage_url','=',''];
           $field   = 'id,video_file';
           $list    = Db::name('tik_kol_video')->field($field)->where($where)->select()->toArray();
           foreach($list as $v){
               $video_file                 = json_decode($v['video_file'],true);
               $message_info['video_id']   = $v['id'];
               $message_info['video_file'] = $video_file;
               //推动数据到队列;
               MqTaskPushLogic::mq_task_push(
                   '',
                   MqQueueName::QUEUE_KOL_VIDEO_LOCAL_QUEUE,
                   $message_info,
                   false
               );
           }
    }




    public function normalizeEmail($email){
        // 替换数学字母符号（U+1D400-U+1D7FF）为常规字符
        $normalized = preg_replace_callback('/[\x{1D400}-\x{1D7FF}]/u', function($match) {
            return chr(ord('a') + (ord($match[0]) - 0x1D41A));
        }, $email);
        return $normalized;
    }


    public function video_local_consumer($info){
        try{
            $video_id = $info['video_id'] ??'';
            $tmp_url  = $info['video_file']['0']['tmp_url'] ??'';
            if(!$tmp_url)  return  true;
            //获取地址;
            $token                  = (new FeiShuMessageLogic())->get_app_access_token();
            $url                    = $tmp_url;
            $res                    = HttpUtil::getFeiShu($url,$token,[]);
            $video_url              = $res['data']['tmp_download_urls']['0']['tmp_download_url']??'';
            //视频上传到OSS服务器;
            $oss_url                = (new UploadTestLogic())->uploadVideoOSS(['url'=>$video_url]);
            if($oss_url){
                Db::name('tik_kol_video')->where(['id'=>$video_id])->update(
                    [
                        'storage_url'=>$oss_url,
                        'update_time'=>date("Y-m-d H:i:s",time()),
                    ]
                );
            }
        }catch (\Exception $e) {
            echo  $e->getMessage();
            return error('失败:' . $e->getMessage());
        }
    }










}